import 'dart:io';

import 'package:extended_text_field/extended_text_field.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/models/entity/osc_user.dart';
import 'package:osc/models/entity/widget_item/publish_tweet_image.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/ui/widgets/common_scaffold.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/tweet/emoji_widget.dart';
import 'package:osc/utils/emoji_util.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/special_text/emoji_text.dart';
import 'package:osc/utils/special_text/my_special_text_span_builder.dart';
import 'package:osc/utils/string_util.dart';

import 'tweet_pick_friend.dart';
import 'tweet_pick_topic.dart';

/// 编辑动弹
class PublishTweet extends StatefulWidget {
  final String originAuthorName;
  final String originContent;
  final int aboutFromTweetId;
  final int aboutId;
  final String tweetContent;

  const PublishTweet({Key key, this.originAuthorName = "", this.originContent = "", this.aboutFromTweetId = 0, this.aboutId: 0, this.tweetContent = ""}) : super(key: key);

  @override
  _PublishTweetState createState() => _PublishTweetState(originAuthorName, originContent, aboutFromTweetId, aboutId, tweetContent);
}

class _PublishTweetState extends State<PublishTweet> {
  final String originAuthorName;
  final String originContent;
  final int aboutFromTweetId;
  int aboutId;
  String tweetContent;

  _PublishTweetState(this.originAuthorName, this.originContent, this.aboutFromTweetId, this.aboutId, this.tweetContent);

  TextEditingController contentEditingController;
  FocusNode focusNodeContent;

  List<PublishTweetImage> images;
  List<OscUser> users;

  ScrollController scrollController;

  bool showEmojiGrid = false;

  HttpRepository httpRepository;

  int aboutType = 0;
  String imgPath;

  String initText = "";

  @override
  void initState() {
    super.initState();
    if(aboutFromTweetId != 0){
      aboutType = 100;
    }
    if(aboutId == 0){
      aboutId = aboutFromTweetId;
    }
    if(aboutFromTweetId != aboutId){
      initText = "//@$originAuthorName :$tweetContent";
    }
    contentEditingController = TextEditingController(text: initText);
    contentEditingController.selection = TextSelection(baseOffset: 0, extentOffset: 0);
    focusNodeContent = FocusNode();
    scrollController = ScrollController();
    scrollController.addListener((){
      hideKeyboard();
    });
    images = List();
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    contentEditingController.dispose();
    focusNodeContent.dispose();
    scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
        title: "发猿圈",
        actions: <Widget>[
          SmallWidgets.buildAction(
            data: "发送",
            onTap: (){
              checkInput();
            },
          ),
        ],
        body: Stack(
          children: <Widget>[
            ListView(
              controller: scrollController,
              children: <Widget>[
                buildExtendedTextField(),
                buildOrigin(),
                Divider(color: Colors.transparent,),
                buildImageGrid(),
              ],
            ),
            Positioned(
              bottom: 0,
              left: 0,
              child: buildBottomButtonAndEmojiGrid(),
            ),
          ],
        ),
    );
  }


  buildExtendedTextField(){
    return ExtendedTextField(
      style: MyTextStyle.TWEET_CONTENT,
      maxLines: 10,
      focusNode: focusNodeContent,
      autofocus: true,
      controller: contentEditingController,
      keyboardType: TextInputType.text,
      maxLength: 160,
      inputFormatters: [LengthLimitingTextInputFormatter(160)],
      decoration: InputDecoration(
        hintText: "请输入内容",
        hintStyle: MyTextStyle.HINT,
        contentPadding: EdgeInsets.symmetric(horizontal: Dimens.gap_view_normal, vertical: Dimens.gap_view_normal),
      ),
      specialTextSpanBuilder: MySpecialTextSpanBuilder(simpleAtTopicEnable: true),
      onTap: (){
        showEmojiGrid = false;
        refreshView();
      },
      textInputAction: TextInputAction.send,
      onSubmitted: (text){
        checkInput();
      },
    );
  }

  buildOrigin(){
    return Offstage(
      offstage: StringUtil.isEmpty(originContent),
      child: Container(
        color: Colors.black12,
        margin: EdgeInsets.all(Dimens.gap_view_big),
        padding: EdgeInsets.all(Dimens.gap_view_big),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text("@$originAuthorName", style: MyTextStyle.USER_LIST_TITLE,),
            Text(originContent, style: MyTextStyle.LIST_BODY, maxLines: 2, overflow: TextOverflow.ellipsis,),
          ],
        ),
      ),
    );
  }

  buildImageGrid(){
    return GridView.builder(
        padding: EdgeInsets.symmetric(horizontal: Dimens.gap_view_normal),
        shrinkWrap: true,
        primary: false,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: Dimens.gap_view_normal,
          mainAxisSpacing: Dimens.gap_view_normal,
        ),
        itemBuilder: (BuildContext context, int index){
          return buildGridItem(index);
        },
      itemCount: images.length,
    );
  }

  buildGridItem(int index){
    PublishTweetImage image = images.elementAt(index);
    return Stack(
      children: <Widget>[
        buildImage(image),
        Positioned(
          right: 0,
          top: 0,
          child: Offstage(
            offstage: image.fake,
            child: GestureDetector(
              onTap: (){
                hideKeyboard();
                delete(index);
              },
              child: Image.asset(PdUtil.getImagePath("ic_unsubscribe"), width: Dimens.view_item_icon_height_normal,fit: BoxFit.contain,),
            ),
          ),
        ),
      ],
    );
  }

  buildImage(PublishTweetImage image){
    return Container(
      width: ScreenUtil.getScreenW(context)/3,
      child: GestureDetector(
        onTap: (){
          hideKeyboard();
          if(image.fake){
            showPickImageSourceDialog();
          } else {

          }
        },
        child: image.fake?buildFakeImage() : buildRealImage(image),
      ),
    );
  }

  buildRealImage(PublishTweetImage image){
    return Image.file(File(image.imagePath), fit: BoxFit.cover,);
  }

  buildFakeImage(){
    return Image.asset(PdUtil.getImagePath("ic_tweet_add"));
  }

  buildBottomButtonAndEmojiGrid(){
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        buildBottom(),
        Offstage(
          offstage: !showEmojiGrid,
          child: EmojiWidget(
              emojiOnTap: (imageName){
                contentEditingController.text += imageName;
                refreshView();
              },
              emojiOnDelete: (){
                String content = contentEditingController.text;
                if(content.endsWith(EmojiText.flagColon) || content.endsWith(EmojiText.flagBracketsR)){
                  if(content.length > 1) {
                    String temp = content.substring(0, content.length - 1);//remove end flag
                    int startFlagIndex = -1;
                    if(content.endsWith(EmojiText.flagColon)){
                      startFlagIndex = temp.lastIndexOf(EmojiText.flagColon);
                    } else {
                      startFlagIndex = temp.lastIndexOf(EmojiText.flagBracketsL);
                    }
                    if(startFlagIndex >= 0){
                      String emojiName = content.substring(startFlagIndex, content.length);
                      if(EmojiUitl.instance.qqEmojiMap.containsKey(emojiName) || EmojiUitl.instance.emojiMap.containsKey(emojiName)){
                        deleteEmoji(startFlagIndex);
                      } else {
                        //delete
                        deleteEmoji(contentEditingController.text.length - 1);
                      }
                    } else {
                      //delete
                      deleteEmoji(contentEditingController.text.length - 1);
                    }
                  } else {
                    //delete
                    deleteEmoji(contentEditingController.text.length - 1);
                  }
                } else {
                  deleteEmoji(contentEditingController.text.length - 1);
                }
              },
          ),
        )
      ],
    );
  }

  deleteEmoji(int endIndex){
    contentEditingController.text = contentEditingController.text.substring(0, endIndex);
    refreshView();
  }

  buildBottom(){
    return Container(
      height: Dimens.view_item_height_big,
      width: ScreenUtil.getScreenW(context),
      padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_normal),
      decoration: BoxDecoration(
        color: Colors.white70,
        border: Border(top: BorderSide(color: Colors.black12), bottom: BorderSide(color: Colors.black12)),
      ),
      child: Row(
        children: <Widget>[
          buildBottomItem("ic_tweet_picture_normal", 0),
          buildBottomItem("ic_tweet_mention_normal", 1),
          buildBottomItem("ic_tweet_topic_normal", 2),
          buildBottomItem("ic_tweet_expression_normal", 3),
        ],
      ),
    );
  }

  buildBottomItem(String imageName, int index){
    return Expanded(
      child: GestureDetector(
        onTap: (){
          hideKeyboard();
          switch(index){
            case 0:
              showEmojiGrid = false;
              showPickImageSourceDialog();
              break;
            case 1:
              showEmojiGrid = false;
              jump2Page(TweetPickFriends());
              break;
            case 2:
              showEmojiGrid = false;
              jump2Page(TweetPickTopic());
              break;
            case 3:
              showEmojiGrid = true;
              break;
          }
          refreshView();
        },
        child: Container(
          color: Colors.transparent,
          child: Image.asset(PdUtil.getImagePath(imageName), height: Dimens.view_item_icon_height_normal,),
        ),
      ),
    );
  }

  showPickImageSourceDialog(){
    double padding = Dimens.gap_view_big;
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context){
          return Container(
            padding: EdgeInsets.only(left: padding, right: padding, bottom: padding),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                buildSheetItem(
                    title: "添加图片",
                    borderRadius: BorderRadius.only(topLeft: buildRadius(), topRight: buildRadius()),
                    height: Dimens.view_item_height_smaller,
                    textStyle: MyTextStyle.LIST_BODY,
                    onTap: (){}
                ),
                SmallWidgets.buildLine(),
                buildSheetItem(
                    title: "相册",
                    borderRadius: BorderRadius.zero,
                    onTap: (){
                      getImage(gallery: true);
                      Navigator.pop(context);
                    }
                ),
                SmallWidgets.buildLine(),
                buildSheetItem(
                    title: "相机",
                    borderRadius: BorderRadius.only(bottomLeft: buildRadius(), bottomRight: buildRadius()),
                    onTap: (){
                      getImage(gallery: false);
                      Navigator.pop(context);
                    }
                ),
                buildSheetItem(
                    title: "取消",
                    borderRadius: BorderRadius.all(buildRadius()),
                    margin: EdgeInsets.only(top: padding),
                    onTap: (){
                      Navigator.pop(context);
                    }
                ),
              ],
            ),
          );
        }
    );
  }

  buildSheetItem({@required String title, @required BorderRadius borderRadius,
    @required Function onTap, EdgeInsetsGeometry margin = EdgeInsets.zero, double height = Dimens.view_button_height_normal, TextStyle textStyle = MyTextStyle.SHEET_BUTTON}){

    double width = ScreenUtil.getScreenW(context);
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: width,
        height: height,
        alignment: Alignment.center,
        margin: margin,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: borderRadius,
        ),
        child: Text(title, style: textStyle,),
      ),
    );
  }

  buildRadius(){
    return Radius.circular(Dimens.view_radius_size_normal);
  }

  addImage(String imagePath){
    if(images.length == 0){
      images.insert(0, PublishTweetImage(imagePath: imagePath));
      images.add(PublishTweetImage(imagePath: "", fake: true));
    } else if(images.length == 9){
      images.removeLast();
      images.add(PublishTweetImage(imagePath: imagePath));
    } else {
      images.insert(images.length - 1, PublishTweetImage(imagePath: imagePath));
    }
    if(mounted){
      setState(() {

      });
    }
  }

  delete(int index){
    images.removeAt(index);
    if(!images.elementAt(images.length-1).fake && images.length > 1){
      images.add(PublishTweetImage(imagePath: "", fake: true));
    } else if(images.length == 1){
      images.removeLast();
    }
    if(mounted){
      setState(() {

      });
    }
  }

  checkInput(){
    if(StringUtil.isEmpty(contentEditingController.text)){
      showTips("请输入内容");
      FocusScope.of(context).requestFocus(focusNodeContent);
    } else {
      publishTweet();
    }
  }

  Future getImage({bool gallery = true}) async {
    File image = await ImagePicker.pickImage(
        source: gallery? ImageSource.gallery : ImageSource.camera,
    );
    addImage(image.path);
//    List<File> images = await MultiMediaPicker.pickImages(source: gallery? ImageSource.gallery : ImageSource.camera);

  }

  hideKeyboard(){
    focusNodeContent.unfocus();
    FocusScope.of(context).requestFocus(FocusNode());
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }

  jump2Page(Widget page){
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result){
      if(result != null && result.success){
        switch(result.id){
          case PopResult.ID_PICK_FRIEND:
            users = result.extract["friends"];
            if(users != null){
              for(OscUser user in users){
                contentEditingController.text += " @${user.name} ";
              }
              refreshView();
            }
            break;

          case PopResult.ID_PICK_TOPIC:
            String topic = result.extract["topic"];
            if(!StringUtil.isEmpty(topic)){
              contentEditingController.text += " #$topic# ";
            }
            break;
        }
      }
    });
  }

  refreshView(){
    if(mounted){
      setState(() {

      });
    }
  }

  publishTweet() async{
    httpRepository.publishTweet(content: contentEditingController.text, aboutFromTweetId: aboutFromTweetId,
        aboutId: aboutId, aboutType: aboutType, imgPath: imgPath).then((resp){
      showTips(resp.message);
      if(resp.success){
        Navigator.pop(context);
      }
    });
  }
}
